<template>
  <div>
    <div><h1>品牌列表</h1></div>

    <div>
      <el-form :inline="true" :model="pageForm" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="pageForm.keyWord"
            placeholder="请输入品牌名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onQuery">搜索</el-button>
          <el-button type="primary" @click="HandlerAdd">添加品牌</el-button>
          <el-button type="danger" @click="BatchDeleteAll">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="brandId" label="ID" width="50" />
        <el-table-column prop="brandName" label="品牌名称" width="120" />
        <el-table-column prop="brandUse" label="使用商品数量" width="120" />
        <el-table-column prop="brandTop" label="排序" width="120" />
        <el-table-column prop="brandStatus" label="状态" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.brandStatus"
              :active-value="0"
              :inactive-value="1"
              @change="onchangeStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" @click="OnHandlerdelete(scope.row)"
              >删除</el-button
            >
            <el-button type="primary" @click="OnHandlerUpdata(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <div style="margin-top: 20px">
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="pageForm.pageNum"
            v-model:page-size="pageForm.pageSize"
            :page-sizes="[2, 4, 6, 8]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加品牌" width="500">
        <el-form :model="form" :rules="rules" ref="ruleFormRef">
          <el-form-item
            label="品牌名称"
            :label-width="formLabelWidth"
            prop="brandName"
          >
            <el-input v-model="form.brandName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="排序"
            :label-width="formLabelWidth"
            prop="brandTop"
          >
            <el-input-number v-model="form.brandTop" :min="0" />
          </el-form-item>
          <el-form-item
            label="状态"
            :label-width="formLabelWidth"
            prop="brandStatus"
          >
            <el-radio-group v-model="form.brandStatus">
              <el-radio :value="0">显示</el-radio>
              <el-radio :value="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getBrandList,
  AddBrand,
  updataStatus,
  deleteBrand,
  DeleteBacth,
} from "../api/api";

import type { FormInstance, FormRules } from "element-plus";

const ruleFormRef = ref<FormInstance>();
const tableData = ref([]);
const total = ref(0);
const pageForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});
//品牌添加
const form = ref({
  brandId: null,
  brandName: "",
  brandStatus: 0,
  brandTop: 0,
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const multipleSelection = ref<any[]>([]);

//校验
const rules = reactive({
  brandName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  brandStatus: [{ required: true, message: "选择状态", trigger: "blur" }],
  brandTop: [{ required: true, message: "请输入排序", trigger: "blur" }],
});

//多选方法
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//批量删除
const BatchDeleteAll = () => {
  ElMessageBox.confirm("删除后数据无法恢复您确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (multipleSelection.value.length == 0) {
        ElMessage.error("请选择数据");
        return;
      }
      DeleteBacth(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//删除
const OnHandlerdelete = (row: any) => {
  ElMessageBox.confirm("删除后数据无法恢复您确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBrand(row.brandId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//查询
const onQuery = () => {
  loadList();
};

//显示弹窗
const HandlerAdd = () => {
  dialogFormVisible.value = true;
  form.value = {
    brandId: null,
    brandName: "",
    brandStatus: null,
    brandTop: null,
  };
};

//修改显示状态
const onchangeStatus = (row: any) => {
  console.log(row);
  updataStatus(row).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//添加品牌
const OnsubmitAdd = () => {
  AddBrand(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//校验添加

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      OnsubmitAdd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pageForm.value.pageNum = val;
  loadList();
};

const loadList = () => {
  getBrandList(pageForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadList();
});
</script>

<style scoped></style>
